﻿using Gym.Application.Common.Interfaces;
using Gym.Domain.Common.EventualConsistency;
using Gym.Domain.RoomAggregate.Events;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Gym.Application.Trainers.Events
{
    public class SessionScheduledEventHandler : INotificationHandler<SessionScheduledEvent>
    {
        private readonly ITrainersRepository _trainersRepository;

        public SessionScheduledEventHandler(ITrainersRepository trainersRepository)
        {
            _trainersRepository = trainersRepository;
        }

        public async Task Handle(SessionScheduledEvent notification, CancellationToken cancellationToken)
        {
            var trainer = await _trainersRepository.GetByIdAsync(notification.Session.TrainerId)
                ?? throw new EventualConsistencyException(SessionScheduledEvent.TrainerNotFound);

            var updateTrainerScheduleResult = trainer.AddSessionToSchedule(notification.Session);

            if (updateTrainerScheduleResult.IsError)
            {
                throw new EventualConsistencyException(
                    SessionScheduledEvent.TrainerScheduleUpdateFailed,
                    updateTrainerScheduleResult.Errors);
            }

            await _trainersRepository.UpdateAsync(trainer);
        }
    }
}
